

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;

public class NIOLatchClient implements Runnable {
    private static CountDownLatch latch = new CountDownLatch(100);

    public Selector selector;

    public NIOLatchClient(int port) {
        SocketChannel sc = null;
        try {
            sc = SocketChannel.open();
            sc.configureBlocking(false);
            selector = Selector.open();
            sc.connect(new InetSocketAddress(8080));
            sc.register(selector, SelectionKey.OP_CONNECT); //监听连接
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private boolean connect(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        try {
            if (sc.isConnectionPending()) {
                sc.finishConnect();
            }
            sc.configureBlocking(false);
            ByteBuffer bb = ByteBuffer.allocate(1024);
            sc.write(bb.wrap("现在几点钟？".getBytes()));
            sc.register(selector, SelectionKey.OP_READ);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private boolean read(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        try {
            ByteBuffer bb = ByteBuffer.allocate(1024);
            sc.read(bb);
            String msg = new String(bb.array(), "UTF-8").trim();
            System.out.println("答复：" + msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


    //@Override
    public void run() {
        /*try{
            latch.await();
            Socket socket = new Socket("localhost",8080);
            System.out.println(Thread.currentThread().getName()+" working......");
            //ByteBuffer bb = new ByteBuffer.allocate(64);
            OutputStream os = socket.getOutputStream();
            os.write("what time is now?".getBytes());
            os.flush();

            Thread.sleep(60*60*1000);
        }catch(Exception e){
            e.printStackTrace();
        }*/

        while (true) {
            try {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    //连接完成
                    if (key.isConnectable()) {
                        connect(key);
                    } else if (key.isReadable()) {
                        read(key);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            NIOLatchClient nc = new NIOLatchClient(8080);
            new Thread(nc).start();
            latch.countDown();
        }
    }
}